package com.enjoylearning.content.service.Jobhandler;


import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.content.feignClient.SearchClient;
import com.enjoylearning.content.feignClient.po.CourseIndex;
import com.enjoylearning.content.mapper.CoursePublishMapper;
import com.enjoylearning.content.model.po.CoursePublish;
import com.enjoylearning.content.service.CoursePublishService;
import com.enjoylearning.messagesdk.model.po.MqMessage;
import com.enjoylearning.messagesdk.service.MessageProcessAbstract;
import com.enjoylearning.messagesdk.service.MqMessageService;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CoursePublishTask extends MessageProcessAbstract {

    @Autowired
    private CoursePublishService coursePublishService;

    @Autowired
    private SearchClient searchClient;

    @Autowired
    private CoursePublishMapper coursePublishMapper;

    //课程发布逻辑
    @Override
    public boolean execute(MqMessage mqMessage) {
        //从message获取数据课程Id
        long courseId = Long.parseLong(mqMessage.getBusinessKey1());
        //向es写索引
        saveCourseIndex(mqMessage, courseId);
        //向redis写缓存
        //课程静态化上传minio
        generateCourseHtml(mqMessage, courseId);
        //返回true表示任务完成
        return true;
    }

    //任务调度
    @XxlJob("coursePublishJobHandler")
    private void coursePublishJobHandler() throws Exception{
        // 分片参数
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        log.debug("shardIndex="+shardIndex+",shardTotal="+shardTotal);
        //参数:分片序号、分片总数、消息类型、一次最多取到的任务数量、一次任务调度执行的超时时间
        process(shardIndex,shardTotal,"course_publish",30,60);

    }

    //生成课程静态化页面并上传至文件系统
    private void generateCourseHtml(MqMessage mqMessage,long courseId) {
        MqMessageService mqMessageService = this.getMqMessageService();
        Long taskId = mqMessage.getId();
        //任务幂等性处理
//        String stageState1 = mqMessage.getStageState1();
        if (mqMessageService.getStageOne(taskId)>0){
            log.debug("课程静态化任务已完成，无需处理");
            return;
        }
        //开始进行课程静态化
        File htmlfile = coursePublishService.generateCourseHtml(courseId);
        if (null == htmlfile){
            XueChengPlusException.cast("生成的静态化页面为空");
        }
        coursePublishService.uploadCourseHtml(courseId, htmlfile);
        //任务处理状态改为1
        mqMessageService.completedStageOne(taskId);
    }

    //保存课程索引信息
    private void saveCourseIndex(MqMessage mqMessage,long courseId) {
        MqMessageService mqMessageService = this.getMqMessageService();
        Long taskId = mqMessage.getId();
        if (mqMessageService.getStageTwo(taskId)>0){
            log.debug("保存课程索引任务已完成，无需处理");
            return;
        }
        //向es写入课程索引
        CoursePublish coursePublish = coursePublishMapper.selectById(courseId);
        CourseIndex courseIndex = new CourseIndex();
        BeanUtils.copyProperties(coursePublish,courseIndex);
        Boolean add = searchClient.add(courseIndex);
        if (!add){
            XueChengPlusException.cast("添加课程文档至es失败,courseId:"+courseId);
        }
        //将消息表状态字段改为1
        mqMessageService.completedStageTwo(taskId);
    }

    //将课程信息缓存至redis
    public void saveCourseCache(MqMessage mqMessage,long courseId){
        log.debug("将课程信息缓存至redis,课程id:{}",courseId);
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }
}
